<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['生产管理', '合格品清单']" currentMenu="合格品申请入库"></crumbs>
    <div class="form-body">
      <a-card title="入库物料" :bordered="false" style="margin-top: 12px">
        <a-table row-key="id" :columns="columns" :data-source="tableData" :pagination="false" :scroll="{ x: columns.length ? columns.length * 160 : 1000, y: 600 }"
          :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }">
          <!-- 数字千分位 -->
          <span slot="num" :title="record.num" slot-scope="text, record">
            {{ numFormat(record.num) }}
          </span>
          <!-- 6个字符控制 超出。。。 -->
          <span slot="goodsName" :title="record.goodsName" slot-scope="text, record">
            {{ subStrText(record.goodsName, 6) }}
          </span>
          <span slot="spec" :title="record.specText" slot-scope="text, record">
            {{ subStrText(record.spec, 6) }}
          </span>
          <span slot="basicUnitText" :title="record.specText" slot-scope="text, record">
            {{ subStrText(record.basicUnitText, 6) }}
          </span>
          <span slot="orderCode" :title="record.orderCode" slot-scope="text, record" class="btn-text" @click="handleDetailOrder(record)">
            {{ record.orderCode }}
          </span>
          <span slot="action" slot-scope="text, record">
            <a @click="handleDelete(record)">删除</a>
          </span>
        </a-table>
        <div class="uni-card" :style="{ background: '#fff' }">
          <div style="display: inline-block">
            <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
            <!-- <span class="pubColor" style="margin: 0 24px">批量完成</span><span class="pubColor">批量作废</span> -->
            <span style="margin-left: 8px">
              <span @click="handleDelete(selectedRowKeys)" class="pubColor" style="margin: 0 10px">批量删除</span>
              {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
              <span @click="clearArr" class="pubColor" style="margin: 0 10px">清空</span>
            </span>
          </div>
          <div style="display: inline-block; float: right">
            <a-pagination :total="total" v-model="current" :page-size-options="pageSizeOptions" :page-size="pageSize" @change="onChangePage"
              @showSizeChange="onShowSizeChange" show-quick-jumper show-size-changer />
          </div>
        </div>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea :maxLength="500" placeholder="请输入" auto-size v-decorator="['remark']" />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
      <div style="margin-top: 12px">
        <Examine @submitProcess="submitProcess" type="0" id="MESS_QUALIFIED_INBOUND_APPLY" ref="examine" />
        <div style="height: 50px"></div>
      </div>
    </div>
    <div class="footer-submit form-footer" :style="{
        position: 'fixed',
        bottom: 0,
        right: 0,
        zIndex: 2,
        padding: '10px 16px',
        width: '100%',
        margin: '0',
      }">
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" :loading="loadingSubmit" class="submitBtn" @click="submitProcess"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import Examine from '@/components/examine'
import {
  productProcessAdd,
  getDictModel,
  productProcessEdit,
  productProcessQueryById,
  pageQueryQualityInboundRecord,
  qualifiedList,
  qualifiedListApplyInBound,
} from '@/api/goodsManagement'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { validateDuplicateValue, getNewColumns, subStrText, numFormat } from '@/utils/util'
export default {
  name: 'qualifiedProductForm', //合格品入库申请
  data() {
    return {
      jkeForm: {
        title: '合格品申请入库',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      numFormat,
      tableList: '',
      subStrText,
      columns: [
        {
          title: '工单编号',
          dataIndex: 'orderCode',
          //   sorter: true,
          key: 'orderCode',
          width: 200,
          ellipsis: true,
          scopedSlots: {
            customRender: 'orderCode',
          },
        },
        {
          title: '产品编号',
          width: 180,
          dataIndex: 'goodsCode',
          key: 'goodsCode',
          ellipsis: true,
        },
        {
          title: '产品名称',
          width: 180,
          align: 'left',
          dataIndex: 'goodsName',
          ellipsis: true,
          scopedSlots: {
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          align: 'left',
          ellipsis: true,
          dataIndex: 'specText',
          scopedSlots: { customRender: 'spec' },
        },
        {
          title: '基本单位',
          align: 'left',
          ellipsis: true,
          dataIndex: 'basicUnitText',
          scopedSlots: { customRender: 'basicUnitText' },
        },
        {
          title: '数量',
          align: 'left',
          ellipsis: true,
          //   sorter: true,
          dataIndex: 'num',
          scopedSlots: { customRender: 'num' },
        },
        {
          title: '操作人',
          dataIndex: 'operatorName',
          key: 'operatorName',
          ellipsis: true,
          scopedSlots: {
            customRender: 'operatorName',
          },
        },
        {
          title: '提交人',
          dataIndex: 'applicantName',
          key: 'applicantName',
          ellipsis: true,
          scopedSlots: {
            customRender: 'applicantName',
          },
        },
        {
          title: '提交时间',
          //   sorter: true,
          width: 180,
          dataIndex: 'applyTime',
          key: 'applyTime',
          ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          // align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      tableData: [],
      selectedRowKeys: [],
      selectArr: [],
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      // 分页
      current: 1,
      total: 100,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      validateDuplicateValue, //自动生成编码
      queryId: '',
      loadingSubmit: false, //防止多次提交
      submitApi: productProcessAdd,
      isEdit: false,
      attachment: '', //附件
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
    }
  },
  components: {
    FileUpload,
    crumbs,
    Examine,
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    // 工单详情
    handleDetailOrder(v) {
      this.$router.push({
        path: '/workOrderDetail',
        query: { id: v.orderId },
      })
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log(selectedRowKeys, selectedRows, 'selectedRowKeys, selectedRows')
      this.tableList = selectedRows
      this.selectedRowKeys = selectedRowKeys
      this.checkBoxStatus()
    },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
        }
        this.list = this.tableData
        this.tableList = this.tableData
        console.log(this.list, 'this.list')
      } else {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
        }
        this.list = ''
        this.tableList = []
        console.log(this.list, 'this.list')
      }
      this.checkBoxStatus()
    },
    // 清空
    clearArr() {
      this.selectedRowKeys = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.tableData) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.requestData()
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize
      this.current = current
      this.requestData()
    },
    // table
    // handleChange(selectedRowKeys, selectedRows) {
    //   console.log(selectedRowKeys, selectedRows,"selectedRowKeys, selectedRows");
    // },

    /* 删除、批量删除 */
    handleDelete(v) {
      if (v instanceof Array) {
        if (v.length > 0) {
          let that = this
          that.$antdConfirm({
            title: '确定要删除产品吗?',
            content: `共选中${v.length}条产品`,
            onOk() {
              v.forEach((item) => {
                that.deleteById(item, that.tableData)
              })
              that.$antdMessage.success('删除成功！')
              that.clearArr()
            },
            onCancel() {},
          })
        } else {
          this.$antdMessage.warning('请勾选需要批量删除的数据')
        }
      } else {
        let that = this
        that.$antdConfirm({
          title: '确定要删除此产品吗?',
          content: ``,
          onOk() {
            that.deleteById(v.id, that.tableData)
            that.$antdMessage.success('删除成功！')
            that.clearArr()
          },
          onCancel() {},
        })
      }
    },
    /**
     * 根据id删除数组项
     * @param {Number} id 需要删除的id
     * @param {Array} list 目标数组
     * @return {Array}
     */
    deleteById(id, list) {
      for (let index = list.length - 1; index >= 0; index--) {
        if (list[index] && list[index].id === id) {
          //注意 ".id"，如果是uid请更换(或通过传参-属性)
          list.splice(index, 1)
        }
      }
      return list
    },
    initForm(id) {
      this.jkeForm.visible = true
      qualifiedList({ ids: id, pageNo: this.current, pageSize: this.pageSize }).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result.records
          this.total = res.result.total
        }
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleSubmit(e)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    // 提交
    handleSubmit(processDataVo) {
      this.form.validateFields((err, values) => {
        console.log(values, 'values form')
        if (!err) {
          if (!this.tableList) {
            this.$antdMessage.error('请选择要入库的物料')
            return
          }
          let parameters = {
            ...values,
            attachment: this.attachment,
            list: this.tableList,
            processDataVo: processDataVo,
          }
          console.log(parameters, 'parameters')
          this.loadingSubmit = true
          qualifiedListApplyInBound(parameters).then((res) => {
            if (res.code == 200) {
              this.loadingSubmit = false
              this.$antdMessage.success('申请入库成功')
              this.$emit('refresh')
              this.goBack()
            } else {
              this.loadingSubmit = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  // height: calc(100vh - 202px);
  overflow-y: scroll;
}
.form-footer {
  margin: 12px -12px 0 -12px;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}
</style>
